package com.ruoyi.zhgd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.zhgd.domain.*;
import com.ruoyi.zhgd.mapper.*;
import com.ruoyi.zhgd.service.*;
import com.ruoyi.zhjd.laboratory.modules.laboratoryMechanicsWGroup.entity.MechanicsWDetailEntity;
import com.ruoyi.zhjd.laboratory.modules.laboratoryMechanicsWGroup.entity.MechanicsWGroupEntity;
import com.ruoyi.zhjd.laboratory.modules.laboratoryMechanicsWGroup.mapper.MechanicsWDetailMapper;
import com.ruoyi.zhjd.laboratory.modules.laboratoryMechanicsWGroup.mapper.MechanicsWGroupMapper;
import com.ruoyi.zhjd.laboratory.modules.laboratoryMechanicsYGroup.entity.MechanicsYDetailEntity;
import com.ruoyi.zhjd.laboratory.modules.laboratoryMechanicsYGroup.entity.MechanicsYGroupEntity;
import com.ruoyi.zhjd.laboratory.modules.laboratoryMechanicsYGroup.mapper.MechanicsYDetailMapper;
import com.ruoyi.zhjd.laboratory.modules.laboratoryMechanicsYGroup.mapper.MechanicsYGroupMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.zhgd.domain.bo.NWarningManagementBo;
import com.ruoyi.zhgd.domain.vo.NWarningManagementVo;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 报警管理Service业务层处理
 *
 * @author cj
 * @date 2023-09-26
 */
@RequiredArgsConstructor
@Service
@DS("sjcj")
public class NWarningManagementServiceImpl implements INWarningManagementService {

    private final NWarningManagementMapper baseMapper;
    private final CollectProductMapper productMapper;
    private final CollectPieceMapper collectPieceMapper;
    private final CollectDosageMapper dosageMapper;
    private final ICollectDosageService iCollectDosageService;
    private final TensionRecordingMapper tensionRecordingMapper;
    private final TensionResultMapper resultMapper;
    private final IZjNLaboratoryTensionRequiresService tensionRequiresService;
    private final GroutingRecordMapper groutingRecordMapper;
    private final GroutingResultMapper groutingResultMapper;
    private final IZjNLaboratoryGroutingRequiresService groutingRequiresService;
    private final MechanicsYGroupMapper mechanicsYGroupMapper;
    private final MechanicsYDetailMapper yDetailMapper;
    private final INLaboratoryMechanicsYGroupService yGroupService;
    private final MechanicsWGroupMapper wGroupMapper;
    private final MechanicsWDetailMapper wDetailMapper;
    private final INLaboratoryMechanicsWGroupService wGroupService;



    /**
     * 查询报警管理
     */
    @Override
    public NWarningManagementVo queryById(String id){
        return baseMapper.selectVoById(id);
    }


    /**
     * 查询报警管理列表
     */
    @Override
    public List<NWarningManagementVo> queryList(NWarningManagementBo bo) {
        LambdaQueryWrapper<NWarningManagement> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NWarningManagement> buildQueryWrapper(NWarningManagementBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NWarningManagement> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeptId() != null, NWarningManagement::getDeptId, bo.getDeptId());
        lqw.eq(bo.getTypeId() != null, NWarningManagement::getTypeId, bo.getTypeId());
        lqw.like(StringUtils.isNotBlank(bo.getTypeName()), NWarningManagement::getTypeName, bo.getTypeName());
        lqw.eq(bo.getDownLowWarning() != null, NWarningManagement::getDownLowWarning, bo.getDownLowWarning());
        lqw.eq(bo.getUpLowWarning() != null, NWarningManagement::getUpLowWarning, bo.getUpLowWarning());
        lqw.eq(bo.getDownMiddleWarning() != null, NWarningManagement::getDownMiddleWarning, bo.getDownMiddleWarning());
        lqw.eq(bo.getUpMiddleWarning() != null, NWarningManagement::getUpMiddleWarning, bo.getUpMiddleWarning());
        lqw.eq(bo.getDownAdvancedWarning() != null, NWarningManagement::getDownAdvancedWarning, bo.getDownAdvancedWarning());
        lqw.eq(bo.getUpAdvancedWarning() != null, NWarningManagement::getUpAdvancedWarning, bo.getUpAdvancedWarning());
        return lqw;
    }

    /**
     * 新增报警管理
     */
    @Override
    public Boolean insertByBo(NWarningManagementBo bo) {
        NWarningManagement add = BeanUtil.toBean(bo, NWarningManagement.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改报警管理
     */
    @Override
    public Boolean updateByBo(NWarningManagementBo bo) {
        NWarningManagement update = BeanUtil.toBean(bo, NWarningManagement.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NWarningManagement entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除报警管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public NWarningManagement queryPageList(Map<String, Object> params) {
        return baseMapper.queryPageList(params);
    }

    @Override
    public List<NWarningManagement> queryHntList(Map<String, Object> params) {
        return baseMapper.queryHntList(params);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatew(NWarningManagement management) {
        baseMapper.insertOrUpdate(management);
    }

    @Override
    public void updateHnt(List<NWarningManagement> management) {
        baseMapper.insertOrUpdateBatch(management);
    }

    /**
     * 模拟采集数据接口
     * 张拉、压浆、压力机、万能机、混凝土分别对应code值为zl,yj,ylj,wnj,hnt;
     * @param code
     */
    @Override
    public void testCollectData(String code,String deptId) {
        switch (code) {
            case "zl":
                testZlCollectData(deptId);
                break;
            case "yj":
                testYjCollectData(deptId);
                break;
            case "ylj":
                testYljCollectData(deptId);
                break;
            case "wnj":
                testWnjCollectData(deptId);
                break;
            case "hnt":
                testHntCollectData(deptId);
                break;
        }
    }

    //混凝土
    private void testHntCollectData(String deptId) {

        //查询主子表数据；
        List<Long> pkIds = productMapper.selectPkids(deptId.equals("undefined") ? null : deptId);
        if (pkIds == null || pkIds.size() == 0) {
            return;
        }
        Random random = new Random();
        Long pkId = pkIds.get(random.nextInt(pkIds.size()));
        CollectProduct vo = productMapper.selectByPkId(pkId.toString());
        //查询盘数据，和数据消耗
        LambdaQueryWrapper<CollectPiece> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectPiece::getParentPkId, vo.getPkId());
        List<CollectPiece> pieceList = collectPieceMapper.selectList(wrapper);
        //查询消耗数据；
        Set<Long> pieces = pieceList.stream().map(CollectPiece::getPkId).collect(Collectors.toSet());
        LambdaQueryWrapper<CollectDosage> dosageWrapper = new LambdaQueryWrapper<>();
        dosageWrapper.in(CollectDosage::getParentPkId, pieces);
        List<CollectDosage> collectDosages = dosageMapper.selectList(dosageWrapper);
        Map<Long, List<CollectDosage>> dosagesMap = collectDosages.stream().collect(Collectors.groupingBy(CollectDosage::getParentPkId));

        //插入主表数据
        vo.setMark("手动采集测试数据：pkId:" + vo.getPkId());
        vo.setPkId(null);
        vo.setWarningStatus(null);
        vo.setProdTimB(new Date());
        vo.setProdTimE(new Date());
        productMapper.insert(vo);
        //插入子表数据
        for (CollectPiece piece : pieceList) {
            List<CollectDosage> dosagesList = dosagesMap.get(piece.getPkId());
            piece.setPkId(null);
            piece.setParentPkId(vo.getPkId());
            collectPieceMapper.insert(piece);
            dosagesList.stream().forEach(e -> {
                e.setParentPkId(piece.getPkId());
                e.setPkId(null);
            });
            dosageMapper.insertBatch(dosagesList);
        }
        iCollectDosageService.test(vo.getPkId().toString());

    }

    //万能机
    private void testWnjCollectData(String deptId) {
        //查询主表
        List<Integer> ids = wGroupMapper.selectIds(deptId.equals("undefined") ? null : deptId);
        if (ids == null || ids.size() == 0) {
            return;
        }
        Integer id = ids.get(new Random().nextInt(ids.size()));
        MechanicsWGroupEntity groupEntity = wGroupMapper.selectById(id);
        //查询子表数据
        LambdaQueryWrapper<MechanicsWDetailEntity> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(MechanicsWDetailEntity::getGroupId, groupEntity.getId());
        List<MechanicsWDetailEntity> mechanicsWDetailEntities = wDetailMapper.selectList(detailWrapper);
        //插入主表数据
        groupEntity.setId(null);
        groupEntity.setCreateDate(null);
        groupEntity.setSysj(new Date());
        groupEntity.setEligible(null);
        wGroupMapper.insert(groupEntity);
        //插入子表
        for (MechanicsWDetailEntity entity : mechanicsWDetailEntities) {
            entity.setGroupId(groupEntity.getId());
            entity.setId(null);
            wDetailMapper.insert(entity);
        }
        //校验数据；
        wGroupService.verifyEligible(groupEntity.getId());
    }

    //压力机
    private void testYljCollectData(String deptId) {
        //查询主表
        List<Integer> ids = mechanicsYGroupMapper.selectIds(deptId.equals("undefined") ? null : deptId);
        if (ids == null || ids.size() == 0) {
            return;
        }
        MechanicsYGroupEntity yGroupEntity = mechanicsYGroupMapper.selectById(ids.get(new Random().nextInt(ids.size())));
        //查询子表
        LambdaQueryWrapper<MechanicsYDetailEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MechanicsYDetailEntity::getGroupId, yGroupEntity.getId());
        List<MechanicsYDetailEntity> yDetailEntities = yDetailMapper.selectList(wrapper);
        //插入主表数据；
        yGroupEntity.setId(null);
        yGroupEntity.setCreateDate(null);
        yGroupEntity.setSysj(new Date());
        yGroupEntity.setEligible(null);
        mechanicsYGroupMapper.insert(yGroupEntity);
        //插入子表数据；
        for (MechanicsYDetailEntity detail : yDetailEntities) {
            detail.setGroupId(yGroupEntity.getId());
            detail.setId(null);
            yDetailMapper.insert(detail);
        }
        //校验数据；
        yGroupService.verifyEligible(yGroupEntity.getId());
    }

    //压浆
    private void testYjCollectData(String deptId) {
        //查询主表；
        List<String> ids = groutingRecordMapper.selectIds(deptId.equals("undefined") ? null : deptId);
        if (ids == null || ids.size() == 0) {
            return;
        }
        GroutingRecord groutingRecord = groutingRecordMapper.selectById(ids.get(new Random().nextInt(ids.size())));
        //查询子表
        LambdaQueryWrapper<GroutingResult> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GroutingResult::getLinkCode, groutingRecord.getLinkCode());
        List<GroutingResult> groutingResults = groutingResultMapper.selectList(wrapper);
        //插入主表；
        String linkCode = UUID.randomUUID().toString().replace("-", "");
        groutingRecord.setId(linkCode);
        groutingRecord.setLinkCode(linkCode);
        groutingRecord.setCreateTime(new Date());
        groutingRecord.setStatus(null);
        groutingRecordMapper.insert(groutingRecord);
        //插入子表；
        groutingResults.stream().forEach(e -> {
            e.setId(UUID.randomUUID().toString());
            e.setLinkCode(linkCode);
        });
        groutingResultMapper.insertBatch(groutingResults);
        //校验数据
        groutingRequiresService.isQualified(linkCode);
    }

    //张拉
    private void testZlCollectData(String deptId) {
        //查主表
        List<String> ids = tensionRecordingMapper.selectIds(deptId.equals("undefined") ? null : deptId);
        if (ids == null || ids.size() == 0) {
            return;
        }
        TensionRecording tension = tensionRecordingMapper.selectById(ids.get(new Random().nextInt(ids.size())));
        //查询子表
        LambdaQueryWrapper<TensionResult> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TensionResult::getLinkCode, tension.getLinkCode());
        List<TensionResult> tensionResults = resultMapper.selectList(wrapper);
        //插入主表数据
        String id = UUID.randomUUID().toString().replace("-", "");
        tension.setId(id);
        tension.setLinkCode(id);
        tension.setTensionTime(new Date());
        tension.setStatus(null);
        tensionRecordingMapper.insert(tension);
        //插入子表数据；
        tensionResults.stream().forEach(e -> {
            e.setId(UUID.randomUUID().toString());
            e.setLinkCode(id);
        });
        resultMapper.insertBatch(tensionResults);
        //数据校验
        tensionRequiresService.isQualified(id);
    }
}
